package com.kun.kunes.util;

import com.kun.kunes.entity.JdContent;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author kun.li
 */
@Component
public class JsoupHelper {

    public List<JdContent> getJdDataList(String keyword) throws Exception {
        HashMap<String, String> cookies = new HashMap<>();
        long time = new Date().getTime();
        String shshshfpx = UUID.randomUUID() + "-" + time;
        cookies.put("shshshfpx", shshshfpx);
        cookies.put("thor", "替换为自己的thor");
        String format = String.format("https://search.jd.com/Search?keyword=%s", keyword);
        Document document = Jsoup.connect(format)
                .cookies(cookies)
                .get();

        Element jGoodsList = document.getElementById("J_goodsList");
        Elements listElementsByTag = jGoodsList.getElementsByTag("li");
        List<JdContent> jdContentList = new ArrayList<>();
        for (Element element : listElementsByTag) {
            // es的唯一ID
            String id = element.attr("data-sku");
            String img = element.getElementsByClass("p-img").get(0).getElementsByTag("img").attr("data-lazy-img");
            String price = element.getElementsByClass("p-price").eq(0).text();
            String describe = element.getElementsByClass("p-name p-name-type-2").get(0).text();
            String shop = element.getElementsByClass("p-shop").get(0).text();
            JdContent jdContent = JdContent.create();
            jdContent.setId(id);
            jdContent.setImg(img);
            jdContent.setName(describe);
            jdContent.setPrice(price);
            jdContent.setShop(shop);
            jdContentList.add(jdContent);
        }

        return jdContentList;
    }


}
